package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.helper.PermissionHelper;
import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨林
 * @create 2023-07-07 11:03 星期五
 * description:
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 获取菜单
     * @return
     */
    @Override
    public List<Permission> getAllMenu() {
        /**
         * 查询所有的权限数据：
         *      以下代码解析：
         *          CAST(id AS SIGNED):数据库查询的表达式
         *              将id字段类型从 int 类型转换成有符号整数（signed）类型
         */
        List<Permission> allPermission =
                permissionMapper.selectList(new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));
        //把权限数据构建成属性结构
        List<Permission> result = PermissionHelper.build(allPermission);
        return result;
    }

    /**
     * 递归删除菜单
     * @param id
     */
    @Override
    public void removeChainById(Long id) {
        //创建封装需要删除的菜单的id的集合
        List<Long> ids = new ArrayList<>();
        //先将自己加入集合
        ids.add(id);
        this.getAllIds(id,ids);
        permissionMapper.deleteBatchIds(ids);
    }

    /**
     * 递归获取需要删除的菜单的id
     * @param id
     * @param ids
     */
    private void getAllIds(Long id, List<Long> ids) {
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getPid,id);
        List<Permission> permissions = permissionMapper.selectList(wrapper);
//        for (Permission permission : permissions) {
//            ids.add(permission.getId());
//            this.getAllIds(permission.getId(),ids);
//        }
        //以上操作用Stream流代替
        permissions.stream().forEach(item -> {
            ids.add(item.getId());
            this.getAllIds(item.getId(),ids);
        });
    }
}
